const { DataTypes, Model } = require('sequelize');
const { sequelize } = require('../config/database');

class Caregiver extends Model {
  // 检查特定日期是否可用
  isAvailableOnDate(date) {
    const checkDate = new Date(date);
    const dayName = checkDate.toLocaleDateString('en-US', { weekday: 'long' }).toLowerCase();
    
    const availability = this.availability || {};
    const schedule = availability.schedule || {};
    const daySchedule = schedule[dayName];
    if (!daySchedule || !daySchedule.available) return false;
    
    // 检查是否在不可用日期列表中
    const unavailableDates = availability.unavailableDates || [];
    const isUnavailable = unavailableDates.some(period => {
      const start = new Date(period.start);
      const end = new Date(period.end);
      return checkDate >= start && checkDate <= end;
    });
    
    return !isUnavailable;
  }

  // 计算服务费用
  calculateServiceCost(serviceType, duration, petCount = 1, isEmergency = false) {
    const pricing = this.pricing || {};
    let rate = pricing.baseRate || 0;
    
    if (serviceType === 'overnight') {
      rate = pricing.overnightRate || pricing.baseRate * 8;
    } else if (isEmergency) {
      rate = pricing.emergencyRate || pricing.baseRate * 1.5;
    }
    
    let totalCost = rate * duration;
    
    // 额外宠物费用
    if (petCount > 1) {
      totalCost += (petCount - 1) * (pricing.additionalPetRate || 10) * duration;
    }
    
    return Math.round(totalCost * 100) / 100;
  }

  // 更新统计信息
  async updateStats(orderData) {
    const stats = this.stats || {
      totalOrders: 0,
      completedOrders: 0,
      cancelledOrders: 0,
      totalEarnings: 0,
      rating: { average: 0, count: 0 }
    };
    
    stats.totalOrders += 1;
    
    if (orderData.completed) {
      stats.completedOrders += 1;
      stats.totalEarnings += orderData.amount || 0;
    }
    
    if (orderData.cancelled) {
      stats.cancelledOrders += 1;
    }
    
    if (orderData.rating) {
      const currentTotal = stats.rating.average * stats.rating.count;
      stats.rating.count += 1;
      stats.rating.average = (currentTotal + orderData.rating) / stats.rating.count;
    }
    
    this.stats = stats;
    return this.save({ validate: false });
  }

  // 虚拟字段: 完成率
  get completionRate() {
    const stats = this.stats || { totalOrders: 0, completedOrders: 0 };
    if (stats.totalOrders === 0) return 0;
    return (stats.completedOrders / stats.totalOrders) * 100;
  }

  // 虚拟字段: 是否完全验证
  get isFullyVerified() {
    const verification = this.verification || {};
    return verification.identityVerified &&
           verification.backgroundCheckPassed &&
           verification.insuranceVerified &&
           verification.referencesVerified;
  }
}

Caregiver.init({
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  // 关联用户
  userId: {
    type: DataTypes.INTEGER,
    allowNull: false,
    unique: true,
    references: {
      model: 'users',
      key: 'id'
    }
  },
  
  // 专业信息 (JSON)
  experience: {
    type: DataTypes.JSON,
    allowNull: false,
    defaultValue: {
      years: 0,
      description: ''
    }
  },
  
  // 专业技能 (JSON)
  skills: {
    type: DataTypes.JSON,
    defaultValue: {
      petTypes: [],
      specialties: [],
      certifications: []
    }
  },
  
  // 服务范围 (JSON)
  serviceArea: {
    type: DataTypes.JSON,
    allowNull: false,
    defaultValue: {
      coordinates: [],
      radius: 10
    }
  },
  
  // 可用性 (JSON)
  availability: {
    type: DataTypes.JSON,
    defaultValue: {
      schedule: {},
      unavailableDates: [],
      maxPetsPerDay: 5,
      acceptsOvernightCare: false,
      acceptsEmergencyCare: false
    }
  },
  
  // 定价 (JSON)
  pricing: {
    type: DataTypes.JSON,
    allowNull: false,
    defaultValue: {
      baseRate: 50,
      overnightRate: 200,
      emergencyRate: 75,
      additionalPetRate: 10
    }
  },
  
  // 验证状态 (JSON)
  verification: {
    type: DataTypes.JSON,
    defaultValue: {
      identityVerified: false,
      backgroundCheckPassed: false,
      insuranceVerified: false,
      referencesVerified: false
    }
  },
  
  // 保险信息 (JSON)
  insurance: {
    type: DataTypes.JSON,
    defaultValue: {}
  },
  
  // 紧急联系人 (JSON)
  emergencyContact: {
    type: DataTypes.JSON,
    allowNull: false,
    defaultValue: {}
  },
  
  // 统计信息 (JSON)
  stats: {
    type: DataTypes.JSON,
    defaultValue: {
      totalOrders: 0,
      completedOrders: 0,
      cancelledOrders: 0,
      totalEarnings: 0,
      rating: {
        average: 0,
        count: 0
      }
    }
  },
  
  // 状态
  status: {
    type: DataTypes.ENUM('pending', 'active', 'inactive', 'suspended', 'banned'),
    defaultValue: 'pending'
  },
  
  // 偏好设置 (JSON)
  preferences: {
    type: DataTypes.JSON,
    defaultValue: {
      autoAcceptOrders: false,
      notificationSettings: {
        newOrders: true,
        orderUpdates: true,
        messages: true,
        reviews: true
      }
    }
  },
  
  // 最后活动时间
  lastActive: {
    type: DataTypes.DATE,
    defaultValue: DataTypes.NOW
  }
}, {
  sequelize,
  modelName: 'Caregiver',
  tableName: 'caregivers',
  timestamps: true,
  indexes: [
    { fields: ['userId'] },
    { fields: ['status'] }
  ]
});

module.exports = Caregiver;
